package cn.wenjie.gd.dao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.wenjie.gd.domain.Medical;
import cn.wenjie.gd.domain.MedicalTop;
import cn.wenjie.gd.util.MedicalPage;
import cn.wenjie.gd.util.UserPage;
import cn.wj.base.dao.BaseDaoImp;

public class MedicalDaoImp extends BaseDaoImp<Medical, Integer> implements MedicalDao {

	@Override
	public Class<Medical> getEntryClass() {
		return Medical.class;
	}

	@Override
	public MedicalPage getPageList(MedicalPage page) {
		StringBuffer sqlbody = new StringBuffer();
		List list = new ArrayList();
		sqlbody.append("  FROM  medical m WHERE 1=1 ");
		if (page.getName() != null && !page.getName().equals("")) {
			sqlbody.append("  AND  m.name LIKE '%" + page.getName() + "%' ");
		}
		if (page.getAmount()!=null) {
			sqlbody.append(" AND m.amount=? ");
			list.add(page.getAmount());
		}
		if (page.getNumber()!= null && !page.getNumber().equals("")) {
			sqlbody.append("  AND  m.number LIKE '%" + page.getNumber() + "%' ");
		}
		if(page.getDeadline()!=null){
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			sqlbody.append("  AND DATEDIFF(m.deadline,'"+format.format(page.getDeadline())+"') <15 ");
		}

		StringBuffer getCountSql = new StringBuffer();
		StringBuffer sql = new StringBuffer();

		getCountSql.append(" SELECT COUNT(*) ");
		getCountSql.append(sqlbody);
		sql.append(" SELECT * ");
		sql.append(sqlbody);
		sql.append(" LIMIT ?,? ");

		int count = queryForInt(getCountSql.toString(), list.toArray());
		page.setTotalRecord(count);
		list.add(page.getStartIndex());
		list.add(page.getPageSize());

		List userList = query(sql.toString(), getEntryClass(), list.toArray());
		page.setResult(userList);
		return page;
	}

	@Override
	public boolean checkNumber(String Number) {
		String parm[] = { Number };
		List list = query(" SELECT * FROM  medical m WHERE m.number=? ", getEntryClass(), parm);
		if (list != null && list.size() > 0) return true;
		return false;
	}
 
	@Override
	public List<Medical> getAllEffective() {
		// TODO Auto-generated method stub
			return query(" SELECT * FROM medical m WHERE m.amount>0 ", getEntryClass());
	}

	@Override
	public List<Medical> getByIds(String ids) {
		// TODO Auto-generated method stub
		return query(" SELECT * FROM medical m WHERE m.id in( "+ids+" ) ",getEntryClass());
	}

	@Override
	public List<MedicalTop> getTodayTop() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		StringBuffer sql=new StringBuffer();
		sql.append(" SELECT  m.number, m.price,m.name, m.producer,m.deadline, m.description, CAST(SUM(quantity) AS SIGNED INT) amount  ");
		sql.append(" FROM  collection c  INNER JOIN collectionsub cs ON c.id=cs.collectionId  INNER JOIN medical m  ON cs.medicalId = m.id  ");
		sql.append(" AND c.date='"+format.format(new Date())+"' GROUP BY cs.medicalId ORDER BY amount DESC LIMIT 0,10 ");
		return query(sql.toString(),MedicalTop.class);
	}
}
